package com.lantzuc.lanucbackend.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>Project: lanuc-backend
 * <p>Powered by Lantz On 2025/10/13
 *
 * @author Lantz
 * @version 1.0
 * @Description DemoFilter
 * @since 1.8
 */
//@WebFilter(urlPatterns = ("/s"))
public class DemoFilter implements Filter {

    private static final String AUTH_HEADER = "Authorization";
    private static final String BEARER_PREFIX = "Bearer ";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("init 初始化拦截器...");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        // 获取请求路径
        String path = httpRequest.getRequestURI();

        // 跳过登录和公开路径
        if (isPublicPath(path)) {
            chain.doFilter(request, response);
            return;
        }

        // 检查认证头
        String authHeader = httpRequest.getHeader(AUTH_HEADER);
        if (authHeader == null || !authHeader.startsWith(BEARER_PREFIX)) {
            sendUnauthorizedError(httpResponse, "缺少认证令牌");
            return;
        }

        // 提取并验证令牌
        String token = authHeader.substring(BEARER_PREFIX.length());
        if (!isValidToken(token)) {
            sendUnauthorizedError(httpResponse, "无效的认证令牌");
            return;
        }

        // 认证通过，继续过滤器链
        System.out.println("用户认证成功，访问路径: " + path);
        chain.doFilter(request, response);
    }

    private boolean isPublicPath(String path) {
        return path.endsWith("/user/login") ||
                path.startsWith("/user/register") ||
                path.endsWith("/user/logout");
    }

    private boolean isValidToken(String token) {
        // 这里应该是实际的令牌验证逻辑
        return token != null && token.length() > 10;
    }

    private void sendUnauthorizedError(HttpServletResponse response, String message)
            throws IOException {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json");
        response.getWriter().write("{\"error\": \"Unauthorized\", \"message\": \"" + message + "\"}");
    }

    @Override
    public void destroy() {
        System.out.println("destroy方法执行...");
    }
}
